#!/usr/bin/env python 
# -*- coding: utf-8 -*-
import os.path

import yaml
class ReadYaml:
    '''
    读取yaml文件
    '''
    def __init__(self,file_path='/configs/defaultConfig.yaml'):
        self.file_path = os.path.dirname(os.path.dirname(__file__)) + file_path

    def read_yaml(self):
        with open(self.file_path,mode='r',encoding='utf-8') as f:
            data = yaml.load(f,Loader=yaml.FullLoader)
        return data

    def get_value(self,key):
        value = self.read_yaml()
        keys = key.split('/')
        m = 0
        for i in range(len(keys)):
            value = value[keys[m]]
            m += 1
        return value

    def write_yaml(self,new_key,new_value):
        '''
        修改yaml文件数据
        :param new_key: 传被替换的key
        :param new_value: 传被替换的value
        '''
        data = self.read_yaml()
        for key in data.keys():
            if key.strip() == new_key:
                data[key] = new_value
                break
            else:
                if isinstance(data[key],dict):
                    for ke in data[key].keys():
                        if ke.strip() == new_key:
                            data[key][ke] = new_value
                            break
                        else:
                            if isinstance(data[key][ke], dict):
                                for k in data[key][ke].keys():
                                    if k.strip() == new_key:
                                        data[key][ke][k] = new_value
                                        break

        with open(self.file_path,mode='w',encoding='utf-8') as f:
            yaml.dump(data,f)


if __name__ == '__main__':
    a = ReadYaml(r'\configs\env_vars.yaml')
    value = a.get_value('reqConfig/headers')

    print(a.read_yaml())


